import { request, parseTime } from "../../utils/util";

Page({
  data: {
    reserveStatus: 'not-reserve',
    dayList: [],
    timeline: [],
    details: {},
    form: {
      venue_id: '', // 场馆id
      sport_id: '', // 预约类型id
      order_date: '', // 预约日期
      amount: 0, // 订单总金额
      yard: [], // 场馆数组（id场馆id，start_time开始时间, end_time结束时间）
    },
    selectedData: {},// 已选的数据
  },
  // 选择场地处理
  doSelectPointer (e) {
    let { parent, parentindex, item, index } = e.currentTarget.dataset;
    let { timeline, selectedData } = this.data;
    if (item.disabled) {
      return false
    }
    if (selectedData[`${parentindex}-${index}`]) {
      delete selectedData[`${parentindex}-${index}`];
    } else {
      selectedData[`${parentindex}-${index}`] = item;
    }
    timeline[parentindex].venues[index].choose = !timeline[parentindex].venues[index].choose;
    this.setData({
      selectedData,
      timeline
    })
    this.createTotal()
  },
  // 计算总价
  createTotal() {
    let { selectedData } = this.data;
    let amount = 0;
    Object.keys(selectedData).forEach(key => {
      amount += selectedData[key].price * 100
    })
    this.setData({
      form: {
        ...this.data.form,
        amount: amount / 100
      }
    })
  },
  selectTime (e) {
    let { item: { date } } = e.currentTarget.dataset;
    this.setData({
      form: {
        ...this.data.form,
        order_date: date
      },
      selectedData: {}
    })
    this.getDetails()
    this.createTotal()
  },
  // 获取详情数据
  getDetails() {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/venue/reserve`,
      params: {
        venue_id: this.options.venue_id,
        date: this.data.form.order_date,
        sport_id: this.options.sport_id,
      },
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          let { order_date } = this.data.form;
          let times = []
          let dayList = []
          data.date.forEach(item => {
            if (item.date === order_date) {
              times = item.times
            }
          })
          if (this.options.dayList) {
            dayList = JSON.parse(this.options.dayList)
          } else {
            dayList = data.date
          }
          dayList.forEach(item => {
            item.date_show = item.date.substr(5).replace('-', '/')
          })
          this.setData({
            details: data,
            dayList
          })
          this.createTimeLine(data, times)
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 改造时间线数据，包含场地信息
  // createTimeLine(data) {
  //   let { order_date } = this.data.form;
  //   let orderDateStart = order_date.replace(/\-/g, '/');
  //   let orderDateEnd = orderDateStart;
  //   // 24点在IOS上不支持，兼容IOS把时间重置为第二天0点
  //   if (data.close_time === '24:00:00') {
  //     orderDateEnd = parseTime(+new Date(orderDateStart) + 86400000, '{y}/{m}/{d}')
  //     data.close_time = '00:00:00'
  //   }
  //   let startTime = +new Date(`${orderDateStart} ${data.open_time}`);
  //   let endTime = +new Date(`${orderDateEnd} ${data.close_time}`);
  //   let timeline = [];
  //   let reserve = data.reserve;
  //   for (; startTime < endTime; startTime += 1800000) {
  //     let start = parseTime(startTime, '{h}:{i}:{s}');
  //     let end = parseTime(startTime + 1800000, '{h}:{i}:{s}');
  //     let price = JSON.parse(JSON.stringify(data.price))
  //     let item = {
  //       startTime: start,
  //       startTimeShow: parseTime(startTime, '{h}:{i}'),
  //       endTime: end,
  //       venues: price.map(value => {
  //         value.startTime = start;
  //         value.endTime = end;
  //         value.disabled = reserve.some(
  //             val => val.yard_price_id === value.id && val.start_time === start
  //         )
  //         // 当前时间以前的禁用
  //         if (Date.now() > +new Date(`${orderDateStart} ${start}`)) {
  //           value.disabled = true
  //         }
  //         value.choose = false
  //         return value;
  //       })
  //     }
  //     timeline.push(item)
  //   }
  //   this.setData({
  //     timeline
  //   })
  // },
  // 改造时间线数据，包含场地信息
  createTimeLine(data, times) {
    let timeline = [];
    let reserve = data.reserve;
    times.forEach(item => {
      item.time_start = item.time_start.replace(/\-/g, '/');
      item.time_start = item.time_start.replace('T', ' ');
      item.time_end = item.time_end.replace(/\-/g, '/');
      item.time_end = item.time_end.replace('T', ' ');
      let start = parseTime(new Date(item.time_start), '{h}:{i}:{s}');
      let end = parseTime(new Date(item.time_end), '{h}:{i}:{s}');
      let price = JSON.parse(JSON.stringify(data.price))
      let obj = {
        startTime: start,
        startTimeShow: parseTime(new Date(item.time_start), '{h}:{i}'),
        endTime: end,
        venues: price.map(value => {
          value.price = item.price[value.id];
          value.startTime = start;
          value.endTime = end;
          value.disabled = reserve.some(
              val => val.yard_price_id === value.id && val.start_time === start
          )
          // 当前时间以前的禁用
          if (Date.now() > +new Date(item.time_start)) {
            value.disabled = true
          }
          value.choose = false
          return value;
        })
      }
      timeline.push(obj)
    })
    this.setData({
      timeline,
      selectedData: {}
    })
  },
  // 校验提交的数据是否合规
  checkData() {
    let { timeline, selectedData } = this.data;
    // keys 是已选的数据在 timeline 的索引
    let keys = Object.keys(selectedData);
    if (keys.length === 0) {
      wx.showToast({
        title: '请选择场地',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (this.options.from === 'order') {
      return true
    }
    if (keys.length <= 1) {
      wx.showToast({
        title: '请至少预定一小时',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    let pass = keys.some(item => {
      let indexs = item.split('-')
      // 上一个
      // let prevItem = null
      // if (timeline[indexs[0] - 1]) {
      //   prevItem = timeline[indexs[0] - 1].venues[indexs[1]]
      // }
      // 下一个
      // 查当前的下一个是否可选，如果可选，必须选一起的，如果不可选或没有了，就让通过
      let nextItem = null
      if (timeline[indexs[0] * 1 + 1]) {
        nextItem = timeline[indexs[0] * 1 + 1].venues[indexs[1]]
      }
      // 强制选择相邻
      if (nextItem && nextItem.choose) {
        return true
      }
      // if ((nextItem && nextItem.choose) || !nextItem || nextItem.disabled) {
      //   return true
      // }
      return false
    })
    if (!pass) {
      wx.showToast({
        title: '请选择相邻时间段的场地',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },
  submit() {
    let pass = this.checkData()
    if (!pass) return false
    let { selectedData } = this.data;
    let yard = [];
    Object.keys(selectedData).forEach(key => {
      yard.push({
        id: selectedData[key].id,
        start_time: selectedData[key].startTime,
        end_time: selectedData[key].endTime,
      })
    })
    if (!yard.length) {
      return false
    }
    this.data.form.yard = yard;
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/venue/orders`,
      method: 'POST',
      data: this.data.form,
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.navigateTo({
            url: `/pages/submitOrder/index?data=${JSON.stringify(data)}`
          })
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onShow () {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    this.getDetails()
  },
  onLoad(options) {
    this.setData({
      form: {
        ...this.data.form,
        order_date: options.date,
        venue_id: options.venue_id,
        sport_id: options.sport_id,
      }
    })
  }
})
